package Filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebFilter("/ceshi/*")
public class FilterTest implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("过滤器来啦！");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("客户端又发出请求啦");
        servletRequest.setCharacterEncoding("utf-8");
        servletResponse.setContentType("text/html;charset=utf-8");
        HttpSession session = ((HttpServletRequest) servletRequest).getSession(false);
        String requestURI = ((HttpServletRequest) servletRequest).getRequestURI();

        if (requestURI.endsWith("/login.jsp") || requestURI.endsWith("/usererror") ||
                requestURI.endsWith("/code") || requestURI.endsWith("/logina")){
            //放行
            filterChain.doFilter(servletRequest,servletResponse);
        }else if (session == null || session.getAttribute("user") == null){
            PrintWriter writer = servletResponse.getWriter();
            writer.write("<script>" +
                    "alert('请正常登录！');" +
                    "window.location.href='login.jsp'" +
                    "</script>");
        }else if (session!=null && session.getAttribute("user")!=null){
            filterChain.doFilter(servletRequest,servletResponse);
        }
    }
    @Override
    public void destroy() {
        System.out.println("过滤器结束啦");
    }


}
